//
//  LocationViewController.m
//  ZBaiduDemo
//
//  Created by 周成龙 on 16/10/26.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "LocationViewController.h"

#import "BaiduMapHeader.h"
#import "LocationPoint.h"

///********************************

@interface LocationViewController () <BMKLocationServiceDelegate, BMKMapViewDelegate>
{
    BMKUserLocation *_lastUserLocation;
}

/** 百度定位地图服务 */
@property (nonatomic, strong)BMKLocationService *locService;

/** 百度地图View */
@property (nonatomic, strong)BMKMapView *mapView;

/** 轨迹线 */
@property (nonatomic, strong) BMKPolyline *polyLine;

/** 显示实时信息 */
@property (weak, nonatomic) IBOutlet UILabel *showLabel;

@end

@implementation LocationViewController

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
}

- (BMKMapView *)mapView {
    if (_mapView == nil) {
        _mapView = [[BMKMapView alloc] initWithFrame:self.view.bounds];
        _mapView.delegate = self;
        //BMKMapTypeNone:空白地图,  BMKMapTypeStandard :标准地图, BMKMapTypeSatellite:卫星地图
        _mapView.mapType = BMKMapTypeStandard;
        // 数字越大，放大倍数越大
        _mapView.zoomLevel = 16;
    }
    return _mapView;
}

- (BMKLocationService *)locService {
    if (_locService == nil) {
        //初始化BMKLocationService
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
        /// 设定定位的最小更新距离。默认为kCLDistanceFilterNone
        _locService.distanceFilter = 10;
        /// 设定定位精度。默认为kCLLocationAccuracyBest。
        _locService.desiredAccuracy = kCLLocationAccuracyBest;
        // 设定最小更新角度。默认为1度，设定为kCLHeadingFilterNone会提示任何角度改变。
        // 转过的角度
        _locService.headingFilter = kCLHeadingFilterNone;
        /// 指定定位是否会被系统自动暂停。默认为YES。只在iOS 6.0之后起作用。
        _locService.pausesLocationUpdatesAutomatically = NO;
        ///指定定位：是否允许后台定位更新。默认为NO。只在iOS 9.0之后起作用。设为YES时，Info.plist中 UIBackgroundModes 必须包含 "location"
        _locService.allowsBackgroundLocationUpdates = YES;
    }
    return _locService;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view insertSubview:self.mapView atIndex:0];
    [self loaction];
    
    [self isFirstLogin];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminateNotification) name:@"applicationWillTerminate" object:nil];
}

- (void)isFirstLogin {
    NSString *launch_mark = [[NSUserDefaults standardUserDefaults] valueForKey:@"launch_mark"];
    if (launch_mark) {
        [self drawWalkPolyline];
    }else {
        [[NSUserDefaults standardUserDefaults] setObject:@"launch_mark" forKey:@"launch_mark"];
    }
}

// 定位
- (IBAction)locationButton:(id)sender {
    [self loaction];
}
// 划路线
- (IBAction)routeButton:(id)sender {
    [self drawWalkPolyline];
}

// 绘制轨迹路线
- (void)drawWalkPolyline {
    
    // 轨迹点数组个数
    NSArray *arr = [LocationPoint queryLocationPoint];
    NSUInteger count = arr.count;
    
    if (count <= 1) {
        return;
    }
    
    // 动态分配存储空间
    // BMKMapPoint是个结构体：地理坐标点，用直角地理坐标表示 X：横坐标 Y：纵坐标
    BMKMapPoint *tempPoints = new BMKMapPoint[count];
    
    // 遍历数组
    LocationPoint *lastPoint = arr[0];
    for (int i = 0; i < arr.count; i ++) {
        LocationPoint *p = arr[i];
        CLLocation *locationA = [[CLLocation alloc] initWithLatitude:p.latitude.floatValue longitude:p.longitude.floatValue];
        CLLocation *locationB = [[CLLocation alloc] initWithLatitude:lastPoint.latitude.floatValue longitude:lastPoint.longitude.floatValue];
        
        double distance = [locationA distanceFromLocation:locationB];
        
        if (distance < 50) {
//            BMKMapPoint locationPoint = BMKMapPointForCoordinate(locationA.coordinate);
//            tempPoints[i] = locationPoint;
            lastPoint = p;
        }else {
//            BMKMapPoint locationPoint = BMKMapPointForCoordinate(locationB.coordinate);
//            tempPoints[i] = locationPoint;
            lastPoint = arr[i-1];
        }
        BMKMapPoint locationPoint = BMKMapPointForCoordinate(locationB.coordinate);
        tempPoints[i] = locationPoint;
    }
    
    
    //移除原有的绘图，避免在原来轨迹上重画
    if(self.polyLine) {
        [self.mapView removeOverlay:self.polyLine];
    }
    NSArray *textureIndex = @[[NSNumber numberWithInt:0]];
    // 通过points构建BMKPolyline
    self.polyLine = [BMKPolyline polylineWithPoints:tempPoints count:count textureIndex:textureIndex];
    
    //添加路线,绘图
    if (self.polyLine) {
        [self.mapView addOverlay:self.polyLine];
    }
    
    // 清空 tempPoints 临时数组
    delete []tempPoints;
    
    // 根据polyline设置地图范围
    [UIView animateWithDuration:0.5 animations:^{
        [self mapViewFitPolyLine:self.polyLine];
    }];
}

- (double)distanceBetweenLocationA:(CLLocation *)locationA LocationB:(CLLocation *)locationB {
    double  distance  = [locationA distanceFromLocation:locationB];
    return  distance;
}

// 根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *)polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [self.mapView setVisibleMapRect:rect];
    self.mapView.zoomLevel = self.mapView.zoomLevel - 0.3;
}

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay {
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.lineWidth = 10;
        polylineView.tileTexture = YES;
        polylineView.keepScale = YES;
        polylineView.isFocus = YES;// 是否分段纹理绘制（突出显示），默认YES
        //加载分段纹理图片，必须否则不能进行分段纹理绘制
        [polylineView loadStrokeTextureImages:@[[UIImage imageNamed:@"dir_arr"]]];
        
        return polylineView;
    }
    return nil;
}

- (void)loaction {
    //先关闭显示的定位图层
    _mapView.showsUserLocation = NO;
    //设置定位的状态
    // BMKUserTrackingModeNone :普通定位模式,  BMKUserTrackingModeHeading  :定位方向模式, BMKUserTrackingModeFollow  :定位跟随模式, BMKUserTrackingModeFollowWithHeading  :定位罗盘模式
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    //显示定位图层
    _mapView.showsUserLocation = YES;
    //启动 LocationService
    [self.locService startUserLocationService];
}

//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation {
//    NSLog(@"heading is %@",userLocation.heading);
    [_mapView updateLocationData:userLocation];
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    _lastUserLocation = userLocation;
    
    NSString *latitude = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.longitude];
    
    self.showLabel.text = [NSString stringWithFormat:@"lat:%@, long:%@ \n header:%@", latitude, longitude, userLocation.heading];
    
    [_mapView updateLocationData:userLocation];
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
    LocationPoint *p = [[LocationPoint alloc] initWithLatitude:latitude longitude:longitude];
    NSArray *arr = [LocationPoint queryLocationPoint];
    LocationPoint *lastPoint = arr.lastObject;
    
//    NSLog(@"==========");
    if (![lastPoint.latitude isEqualToString:latitude] || ![lastPoint.longitude isEqualToString:longitude]) {
        [p insertPoint];
    }
}

- (void)willStartLocatingUser {
//    NSLog(@"start locate");
}
- (void)didStopLocatingUser {
//    NSLog(@"stop locate");
}
- (void)didFailToLocateUserWithError:(NSError *)error {
//    NSLog(@"location error");
}
- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}
- (void)applicationWillTerminateNotification {
    NSString *latitude = [NSString stringWithFormat:@"%f", _lastUserLocation.location.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", _lastUserLocation.location.coordinate.longitude];
    LocationPoint *p = [[LocationPoint alloc] initWithLatitude:latitude longitude:longitude];
    [p insertPoint];
}

@end
